<?php

namespace app\api\controller;

use addons\third\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\UserLevel;
use app\common\model\UserLevelScoreLog;
use app\common\model\UserRoll;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use wechat\Wechat;
use app\common\model\User as UserModel;
use wechat\WXBizDataCrypt;
use app\api\service\UserService;

/**
 * 会员接口
 */
    class User extends Api
    {
        protected $noNeedLogin = ['third','wxOpenPlatformOauth','wxOfficialAccountBaseLogin','appleIdOauth','accountLogin','getWxMiniProgramSessionKey'];
        protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        // if (!Config::get('fastadmin.usercenter')) {
        //     $this->error(__('User center already closed'));
        // }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $data = (new UserModel())->get($this->auth->id);
        // 如果没有数据，或账户类型为商户，则返回code为0
        if (!isset($data['user_type']) || $data['user_type']==1) {
            $this->error('非用户角色',$data);
        }
        // $totalWallet = (new \app\common\model\UserWalletLog())
        //     ->where(['user_id' => $this->auth->id, 'wallet' => ['>', 0], 'status' => 1])
        //     ->sum('wallet');
        // $data['total_wallet'] = 0;
        $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['user_id'=>$this->auth->id])->field('real_name')->order('id DESC')->find();
        if (isset($user_withdrawal_log['real_name']) && $user_withdrawal_log['real_name']) {
            $data['username'] = $user_withdrawal_log['real_name'];
        } else {
            $data['username'] = '';
        }
        if ($data['beans']<0) $data['beans']=0;
        $this->success('', $data);
    }

    public function info()
    {
        $data = UserModel::get($this->auth->id);
        $user_withdrawal_log = Db::name('user_withdrawal_log')->where(['user_id'=>$this->auth->id])->field('real_name')->order('id DESC')->find();
        if (isset($user_withdrawal_log['real_name']) && $user_withdrawal_log['real_name']) {
            $data['username'] = $user_withdrawal_log['real_name'];
        } else {
            $data['username'] = '';
        }
        if ($data['beans']<0) $data['beans']=0;
        $this->success('', $data);
    }

    public function userData()
    {
        $data = $this->auth->getUserinfo();
        if (isset($data['user_type']) && $data['user_type']==2) {
            $this->success('', $data);
        } else {
            $this->error('非用户角色', $data);
        }
    }

    public function bindMobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('code');
        if (!$mobile || !$captcha) {
            $this->error('请把信息补充完整');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error('手机号格式错误');
        }
        if ($mobile=='19370777623') {
            $this->error('绑定手机号失败，请联系客服~');
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->where('user_type',2)->find()) {
            $this->error('手机号已存在');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        Db::startTrans();
        try {
            $verification = $user->verification;
            $verification->mobile = 1;
            $user->verification = $verification;
            $user->mobile = $mobile;
            if ($user->level==0) {
                $user->level = 1;
            }
            $user->save();
            // (new UserService())->setBlackList($user->id,$mobile,'电话拉黑');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('失败');
        }
        Sms::flush($mobile, 'changemobile');

        $this->success('手机号绑定成功');
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * app微信登录
     * @DateTime 2023-04-20T15:41:25+0800
     * @return   [type]                   [description]
     */
    public function wxOpenPlatformOauth()
    {
        $access_token = input('access_token', '','htmlspecialchars');
        $expires_in = input('expires_in', '','htmlspecialchars');
        $refresh_token = input('refresh_token', '','htmlspecialchars');
        $openid = input('openid', '','htmlspecialchars');
        $scope = input('scope', '','htmlspecialchars');
        $unionid = input('unionid', '','htmlspecialchars');
        if (!$unionid) {
            $this->error('获取用户信息有误', '', 400, 'json', ['statuscode' => 200]);
        }
        $event = input('event', '','htmlspecialchars');
        $pid = input('pid/d', 0);
        if (!$openid) $this->error('自动登陆失败');
        $puser = (new UserModel())->where(['id' => $pid])->field('status')->find();
        if ($puser['status']=='hidden') {
            $this->error(__('授权失败，请联系客服'));
        }
        $appid = Config::get('wx_kf.appid');
        $appSecret = Config::get('wx_kf.appsecret');

        $wechat = new Wechat($appid, $appSecret);
        $wechatUserInfo = $wechat->getUserInfo2($access_token,$openid);
        \think\Log::write(json_encode($wechatUserInfo));
        // $wechatUserInfo['openid'] = 'oyBpS6RfdATXvwGoY8dH66DrEteU';
        // $wechatUserInfo['nickname'] = 'wz12013';
        // $wechatUserInfo['sex'] = '0';
        // $wechatUserInfo['language'] = '';
        // $wechatUserInfo['city'] = '';
        // $wechatUserInfo['province'] = '';
        // $wechatUserInfo['country'] = '';
        // $wechatUserInfo['headimgurl'] = 'https://thirdwx.qlogo.cn/mmopen/vi_32/CbCVj7icpueVAfSnQqU9aCn9v2Xbo4MtWONya7MweqEiav1dhSEbHHAQGsqBYFtOgHHwAibrZPdKvQro75ETzyibXQ/132';
        // $wechatUserInfo['privilege']['unionid'] = 'oC_s565kq7a-XFjUITxyOZdHBcmA';
        if (!isset($wechatUserInfo['openid']) || !$wechatUserInfo['openid']) {
            $this->error('获取用户信息失败', '', 400, 'json', ['statuscode' => 200]);
        }
        $nickname = $wechatUserInfo['nickname'];
        $sex = $wechatUserInfo['sex'];
        $language = $wechatUserInfo['language'];
        $city = $wechatUserInfo['city'];
        $province = $wechatUserInfo['province'];
        $country = $wechatUserInfo['country'];
        $headimgurl = $wechatUserInfo['headimgurl'];
        Db::startTrans();
        try {
            $user = (new UserModel())->where(['unionid' => $unionid,'user_type'=>2])->find();
            if ($user) {
                if ($user->status == 'cancel') {
                    $this->error('无法登录，请联系客服');
                } elseif ($user->status == 'hidden') {
                    $this->error('无法登录，请联系客服');
                }
                // third表有没有数据
                $third = (new Third())->where(['openid'=>$openid,'platform'=>'app'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'app';
                    $thirddata['openname'] = $nickname;
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = $openid;
                $password = Random::alnum();
                $extend = [
                    'openid' => $openid,
                    'nickname' => $nickname,
                    'avatar' => $headimgurl,
                    'gender' => $sex,
                    'user_type' => 2,
                    'pid' => $pid > 0 ? $pid : 0,
                    'unionid' => $unionid ?? ''
                ];
                $mobile = '';
                if ($extend['unionid'] != '') {
                    $third = (new Third())->alias('t')->join('chbc_user u','t.user_id=u.id')->field('u.*,t.user_id')->where(['t.unionid'=>$extend['unionid']])->order('u.avatar desc')->find();
                    if ($third && $third['user_id'] > 0) {
                        if ($third['mobile'] != '') $mobile = $third['mobile'];
                        if ($third['nickname'] != '' && $third['avatar'] != '') {
                            $extend['nickname'] = $third['nickname'];
                            $extend['avatar'] = $third['avatar'];
                        }
                    }
                }
                $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                $user = (new UserModel())->where(['unionid' => $unionid,'openid' => $openid,'user_type'=>2])->find();
                // third表有没有数据
                $third = (new Third())->where(['openid'=>$openid,'platform'=>'app'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'app';
                    $thirddata['openname'] = $nickname;
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
                // 二维码
                // $user->qrcode = $this->createQrcode($user['id']);
                // $user->save();
                // 如果已经加微信客服了，更新会员任务和会员等级
                $qywx_receive = Db::name('qywx_receive')->where(['unionid'=>$unionid,'ChangeType'=>'add_external_contact','user_id'=>0])->find();
                if ($qywx_receive) {
                    $UserService = new UserService();
                    $return = $UserService->oneLevel($this->auth->id);
                    if (!$return) {
                        Db::rollback();
                        $this->error('更新会员任务和会员等级失败');
                    }
                    Db::name('qywx_receive')->where(['id'=>$qywx_receive['id']])->update(['user_id'=>$this->auth->id]);
                }
            }
            $user['token'] = $this->auth->getToken();
            if (isset($this->auth->id) && $this->auth->id) {
                // var_dump($Luckdraw->getFp());exit;
                // 发饭票
                $Luckdraw = new \app\api\controller\Luckdraw();
                $Luckdraw->getFp();
            }
            Db::commit();
            $this->success('登陆成功',$user);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
    }

    /**
     * h5登录
     * @DateTime 2023-04-20T15:21:15+0800
     * @return   [type]                   [description]
     */
    public function wxOfficialAccountBaseLogin()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform", 'wechat');
        $code = input('code');
        $pid = input('pid/d', 0);
        $puser = (new UserModel())->where(['id' => $pid])->field('status')->find();
        if ($puser['status']=='hidden') {
            $this->error(__('授权失败，请联系客服'));
        }
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $platformObj = $app->{$platform};
        $result = $platformObj->getAccessToken($code);
        \think\Log::write('用户端h5获取code:'.json_encode($result,JSON_UNESCAPED_UNICODE));
        $openid = $result['openid'];
        if (empty($openid)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        try {
            $wechatUserInfo = $platformObj->getUserInfo($result);
            \think\Log::write('用户端h5微信授权信息:'.json_encode($wechatUserInfo,JSON_UNESCAPED_UNICODE));
            // var_dump($wechatUserInfo);exit;
            $unionid = isset($wechatUserInfo['userinfo']['unionid'])?$wechatUserInfo['userinfo']['unionid']:'';
            // $userWechat = (new Third())->where(['platform' => 'h5', 'unionid' => $unionid])->find();
            // if ($userWechat && $userWechat['user_id'] > 0) {
            $user = (new UserModel())->where(['unionid' => $unionid,'user_type'=>2])->find();
            // }
            if (isset($user) && $user) {
                if ($user->status == 'cancel') {
                    $this->error('无法登录，请联系客服');
                } elseif ($user->status == 'hidden') {
                    $this->error('无法登录，请联系客服');
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = getUniqueUsername();
                $extend = [
                    'openid' => $openid,
                    'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                    'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                    'gender' => 0,
                    'pid' => $pid,
                    'unionid' => $unionid ?? '',
                    'user_type' => 2
                ];
                $ret = $this->auth->register($username, Random::alnum(), '', '', $extend);
                // 如果已经加微信客服了，更新会员任务和会员等级
                $qywx_receive = Db::name('qywx_receive')->where(['unionid'=>$unionid,'ChangeType'=>'add_external_contact','user_id'=>0])->find();
                if ($qywx_receive) {
                    $UserService = new UserService();
                    $return = $UserService->oneLevel($this->auth->id);
                    if (!$return) {
                        Db::rollback();
                        $this->error('更新会员任务和会员等级失败');
                    }
                    Db::name('qywx_receive')->where(['id'=>$qywx_receive['id']])->update(['user_id'=>$this->auth->id]);
                }
            }
            //用户注册成功
            if ($ret) {
                $userInfo = (new UserModel())->where('id', $this->auth->id)->find();
                $userWechat = (new Third())->where(['user_id' => $userInfo['id'], 'openid' => $openid])->find();
                if (!$userWechat) {
                    $data = $userInfo->toArray();
                    //微信用户表添加记录
                    $data['platform'] = 'h5';
                    $data['user_id'] = $data['id'];
                    $data['openid'] = $openid;
                    $data['access_token'] = '';
                    $data['refresh_token'] = '';
                    $data['expires_in'] = 3600 * 24 * 7;
                    $data['unionid'] = $unionid ?? '';
                    unset($data['id']);
                    Service::connect('wechat', $data);
                }
                $userInfo = $this->auth->getUserinfo();
                $userInfo['session_key'] = '';
                Db::commit();
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
        $this->success('', $data);
    }

    /**
     * 小程序登录
     * @return [type] [description]
     */
    public function getWxMiniProgramSessionKey()
    {
        $code = input('code', '');
        $pid = input('pid/d', 0);
        if (!$code) $this->error('自动登陆失败');
        $appid = Config::get('xcx.appid');
        $appSecret = Config::get('xcx.appsecret');

        $wechat = new Wechat($appid, $appSecret);
        $wechatUserInfo = $wechat->code2Session($code);
        \think\Log::write('小程序userinfo:'.json_encode($wechatUserInfo));
        if (isset($wechatUserInfo['errcode']) && $wechatUserInfo['errcode'] !== 0) {
            $this->error('获取用户信息失败', '', 400, 'json', ['statuscode' => 200]);
        }
        $sessionKey = $wechatUserInfo['session_key'];
        $openid = $wechatUserInfo['openid'];
        $unionid = $wechatUserInfo['unionid'];
        // $sessionKey = 'pEJRIRy0rBz7DjC0T+FmyA==';
        // $openid = 'op5kO5QrbSP9pWPY0aSgCOrWEwN8';
        // $unionid = 'oC_s565kq7a-XFjUITxyOZdHBcmA';
        if (empty($openid) || empty($sessionKey)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        try {
            $user = (new UserModel())->where(['unionid' => $unionid,'user_type'=>2])->find();
            if ($user) {
                if ($user->status == 'cancel') {
                    $this->error('无法登录，请联系客服');
                } elseif ($user->status == 'hidden') {
                    $this->error('无法登录，请联系客服');
                }
                // third表有没有数据
                $third = (new Third())->where(['openid'=>$openid,'platform'=>'miniprogram'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'miniprogram';
                    $thirddata['openname'] = '';
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = $openid;
                $password = Random::alnum();
                $extend = [
                    'openid' => $openid,
                    'nickname' => '微信用户',
                    'pid' => $pid > 0 ? $pid : 0,
                    'unionid' => $unionid ?? '',
                    'user_type'=>2
                ];
                $mobile = '';
                if ($extend['unionid'] != '') {
                    $third = (new Third())->alias('t')->join('chbc_user u','t.user_id=u.id')->field('u.*,t.user_id')->where(['t.unionid'=>$extend['unionid']])->order('u.avatar desc')->find();
                    if ($third && $third['user_id'] > 0) {
                        if ($third['mobile'] != '') $mobile = $third['mobile'];
                        if ($third['nickname'] != '' && $third['avatar'] != '') {
                            $extend['nickname'] = $third['nickname'];
                            $extend['avatar'] = $third['avatar'];
                        }
                    }
                }
                $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                if (!$ret) {
                    $this->error('注册失败，请联系管理员');
                }
                $user = (new UserModel())->where(['openid' => $openid,'unionid' => $unionid,'user_type'=>2])->find();
                // third表有没有数据
                $third = (new Third())->where(['openid'=>$openid,'platform'=>'miniprogram'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'miniprogram';
                    $thirddata['openname'] = $extend['nickname'];
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
            }
            $user['token'] = $this->auth->getToken();
            Db::commit();
            $this->success('登陆成功',$user);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
    }

    /**
     * 生产二维码
     * @DateTime 2023-04-11T16:30:44+0800
     * @return   [type]                   [description]
     */
    public function createQrcode($uid)
    {
        $config = get_addon_config('qrcode');
        $params = array_intersect_key($config, array_flip(['text', 'size', 'padding', 'errorlevel', 'foreground', 'background', 'logo', 'logosize', 'logopath', 'label', 'labelfontsize', 'labelalignment']));
        $params['text'] = 'https://' . $_SERVER['SERVER_NAME'] . '/h5?pid=' . $uid;
        $params['label'] = $this->request->get('label', $config['label'], 'trim');

        $qrCode = \addons\qrcode\library\Service::qrcode($params);


        // 写入到文件
        if ($config['writefile']) {
            $dirPath = '/uploads/qrcode/';
            $qrcodePath = ROOT_PATH . 'public' . $dirPath;
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }
            if (is_really_writable($qrcodePath)) {
                $imgName = md5(implode('', $params)) . '.' . $config['format'];
                $filePath = $qrcodePath . $imgName;
                $qrCode->writeFile($filePath);
            }
        }
        return $dirPath.$imgName;
    }

    /**
     * 海报背景图
     * @DateTime 2023-04-11T17:09:59+0800
     * @return   [type]                   [description]
     */
    public function poster()
    {
        $list = [];
        $imgs = Db::name('config')->where('name','poster')->value('value');
        if ($imgs) {
            $arr = explode(',', $imgs);
            foreach ($arr as $key => $value) {
                $list[] = config('upload_domain').$value;
            }
        }
        $this->success('',$list);
    }

    /**
     * 激活VIP
     */
    public function activationVip()
    {
        try {
            $user = (new UserModel())->where('id', $this->auth->id)->find();
            if ($user->is_vip == 1) $this->success('已激活', null);
            $user->level = 1;
            $user->is_vip = 1;
            $user->save();
            $this->success('激活成功', null);
        } catch (Exception $e) {
            $this->error('激活失败');
        }
    }

    /**
     * 优惠券列表
     * @DateTime 2023-04-11T17:14:20+0800
     * @return   [type]                   [description]
     */
    public function rollList()
    {
        $status = input('status/d',0);//1-正常2-已使用3-过期   
        $page = input('page',1);
        $pageSize = 20;
        if (!in_array($status, [1,2,3])) {
            $this->error('参数有误');
        }
        $where['user_id'] = $this->auth->id;
        $where['status'] = $status;
        $list = [];
        $user_roll = Db::name('user_roll')->where($where)->order('id DESC')->page($page,$pageSize)->select();
        foreach ($user_roll as $key => $value) {
            $list[$key]['roll_type'] = $value['roll_type'];
            $list[$key]['roll_name'] = $value['roll_name'];
            $list[$key]['source'] = $value['source'];
            $list[$key]['id'] = $value['id'];
            $list[$key]['status'] = $value['status'];
            $list[$key]['create_dt'] = date('Y.m.d',strtotime($value['create_dt']));
            $list[$key]['expire_time'] = date('Y.m.d',$value['expire_time']);
            $list[$key]['img'] = '';
            $img = Db::name('config')->where('name',$value['roll_type'].'_pic')->value('value');
            if ($img) {
                $list[$key]['img'] = config('upload_domain').$img;
            }
        }
        $this->success('',$list);
    }

    // 券是否存在
    public function rollExist()
    {
        $type = input('type','');
        if (!$type) {
            $this->error('请求有误');
        }
        $roll = UserRoll::where(['roll_type'=>$type,'user_id'=>$this->auth->id,'status'=>1,'expire_time'=>['>',time()]])->value('sum(roll_num)');
        if (!$roll) {
            $this->success('不存在',0);
        }
        $this->success('存在',$roll);
    }

    /**
     * 注销
     * @DateTime 2023-05-05T21:09:58+0800
     * @param    string                   $value [description]
     * @return   [type]                          [description]
     */
    public function cancellation()
    {
        $user = UserModel::get($this->auth->id);
        if (!$user) {
            $this->error('注销失败');
        }
        // 如果吃豆为负，不能注销
        if ($user['beans']<0) $this->error('注销失败，请联系管理员');
        $order = Db::name('play_order')->field('id')->where('user_id='.$this->auth->id.' and order_status in (1,2,-5,-7,-8,6)')->find();
        if ($order) $this->error('注销失败，您还有一笔订单没有完成');
        // 如果完成最后一笔订单不超过3天，不能注销
        $order = Db::name('play_order')->field('create_dt')->where('user_id='.$this->auth->id.' and order_status=3')->order('id DESC')->find();
        if (isset($order['create_dt']) && strtotime($order['create_dt'])) {
            if (time()-strtotime($order['create_dt'])<3*86400) $this->error('注销失败，请联系管理员');
        }
        $user->status = 'cancel';
        $user->updatetime = time();
        $user->save();
        $this->success('注销成功');
    }

    /**
     * [appleIdOauth description]
     * @return [type] [description]
     */
    public function appleIdOauth()
    {
        $obj = new \app\api\controller\Index();
        if ($obj->isIosLogin()==1) {
            $this->error('您好，请使用微信登录哦~');
        }
        $unionid = input('openId','');
        $openid = input('openId','');
        $familyName = input('familyName','');
        $giveName = input('giveName','');
        if (!$unionid) {
            $this->error('参数有误~');
        }
        $username = $familyName.$giveName;
        $extend = [
            'nickname' => $username,
            'avatar' => "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
            'gender' => 0,
            'unionid' => $unionid,
            'openid' => $openid,
            'user_type' => 2
        ];
        $mobile = '';
        $ret = $this->auth->register($username, Random::alnum(), '', $mobile, $extend);
        
        //用户注册成功
        if ($ret) {
            $userInfo = (new UserModel())->where('id', $this->auth->id)->find();
            $userWechat = (new Third())->where(['user_id' => $userInfo['id'], 'openid' => $openid])->find();
            if (!$userWechat) {
                $data = $userInfo->toArray();
                //微信用户表添加记录
                $data['platform'] = 'app';
                $data['user_id'] = $data['id'];
                $data['openid'] = $openid;
                $data['access_token'] = '';
                $data['refresh_token'] = '';
                $data['expires_in'] = 3600 * 24 * 7;
                $data['unionid'] = $unionid ?? '';
                unset($data['id']);
                Service::connect('wechat', $data);
            }
            $userInfo = $this->auth->getUserinfo();
            $userInfo['session_key'] = '';
            Db::commit();
            $this->success(__('Logged in successful'), $userInfo);
        } else {
            Db::rollback();
            $this->error($this->auth->getError());
        }
        $user = (new UserModel())->where(['unionid' => $unionid,'openid' => $openid,'user_type'=>2])->find();
        $user['token'] = $this->auth->getToken();
        // $user = UserModel::get(2);
        // $user['token'] = Api::getRefreshtoken(2); 
        $this->success('登陆成功',$user);
    }



    public function accountLogin()
    {
        $phone = input('phone','');
        $passwd = input('passwd','');
        if ($phone!='15395101520' || $passwd!='123456') {
            $this->error('账号或密码错误');
        }
        Db::startTrans();
        try {
            $user = (new UserModel())->where(['nickname' => 'wz12013','user_type'=>2])->find();
            if (isset($user) && $user) {
                if ($user->status != 'normal') {
                    $this->error('');
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            }
            //用户注册成功
            if ($ret) {
                $userInfo = (new UserModel())->where('id', $this->auth->id)->find();
                $userWechat = (new Third())->where(['user_id' => $userInfo['id'], 'openid' => $userInfo['openid']])->find();
                if (!$userWechat) {
                    $data = $userInfo->toArray();
                    //微信用户表添加记录
                    $data['platform'] = 'h5';
                    $data['user_id'] = $data['id'];
                    $data['openid'] = $openid;
                    $data['access_token'] = '';
                    $data['refresh_token'] = '';
                    $data['expires_in'] = 3600 * 24 * 7;
                    $data['unionid'] = $unionid ?? '';
                    unset($data['id']);
                    Service::connect('wechat', $data);
                }
                $userInfo = $this->auth->getUserinfo();
                $userInfo['session_key'] = '';
                Db::commit();
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
        $this->success('', $data);
    }

    public function setAvatar()
    {
        $avatar = input('avatar','','htmlentities,htmlspecialchars,trim');
        $nickname = input('nickname','','htmlentities,htmlspecialchars,trim');
        $user = UserModel::where(['id'=>$this->auth->id,'user_type'=>2])->find();
        if (!$user) {
            $this->error('用户不存在');
        }
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        $user->updatetime = time();
        $user->save();
        $this->success('成功');
    }


    public function wechatInfo()
    {
        $appid = Config::get('wx_gzh.appid');
        $appSecret = Config::get('wx_gzh.appsecret');
        $openid = '';
        $unionid = \app\common\model\User::where('id',$this->auth->id)->value('unionid');
        if ($unionid) {
            $openid = Db::name('third')->where(['unionid'=>$unionid,'platform'=>'h5','user_id'=>$this->auth->id])->value('openid');
        }
        if (!$openid) {
            $this->success('没有关注',['status'=>0]);
        } else {
            $this->success('已关注',['status'=>1]);
        }
    }
}
